package com.qvtu.poetry.common.Interceptor;

import com.qvtu.poetry.utils.JwtUtil;
import com.qvtu.poetry.utils.ThreadLocalUtil;
import com.auth0.jwt.exceptions.TokenExpiredException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    // 请求进入 Controller 之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 打印被拦截的实际路径与方法，便于定位是否匹配到放行规则
        System.out.println("[LoginInterceptor] preHandle URI=" + request.getRequestURI() + ", method=" + request.getMethod());
        String token = request.getHeader("Authorization");
        if (token == null || token.isBlank() || !token.startsWith("Bearer ")) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未登录\"}");
            response.setStatus(401);
            System.out.println("不存在token就 -----------拦截了  返回401 ------------");
            return false; // 中断请求
        }
        // 解析完存入jwt
        String jwt = null;
        jwt = token.substring(7); // 去掉前面7个字符   "Bearer " 部分
        System.out.println("---------jwt: " + jwt);
        try {
            Map<String, Object> tokenMap = JwtUtil.parseToken(jwt);
            ThreadLocalUtil.set(tokenMap);

            // 在后续代码中获取ThreadLocal中的信息
            Map<String, Object> userInfo = ThreadLocalUtil.get();
            System.out.println("---------User Info from ThreadLocal: " + userInfo);
        } catch (TokenExpiredException e) {
            System.out.println("token过期 -----------拦截了  返回401 ------------");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"登录过期\"}");
            response.setStatus(401);
            return false;
        } catch (Exception e) {
            System.out.println("解析token失败 -----------拦截了  返回401 ------------");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未登录\"}");
            response.setStatus(401);
            return false;
        }
        return true;
    }

    // Controller 方法执行完成后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 可选操作，如添加响应头
        response.setHeader("X-Custom-Header", "interceptor-added");
    }

    // 整个请求完成（包括视图渲染）后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 可用于资源清理、日志记录等
        System.out.println("【拦截器】请求结束：" + request.getRequestURI());
    }


}
